<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">




  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JAVA bean spring 对象拷贝," />










<meta name="description" content="在项目中，尤其是在服务层，经常要将服务中的Dto实体对象拷贝到Entity对象用于前端展示。反过来也是一样，需要将前端请求对象转换为服务端的数据对象。现在市面上有很多这样的工具包，比如spring框架中就自带了BeanUtils，使我们进行这样的数据操作十分简单快捷。但是一直以来却没有关注到对象属性的拷贝性能问题，最近在想：单个对象的拷贝是快速的，可以不在意太多性能问题，可是如果数量级变大了会怎样">
<meta property="og:type" content="article">
<meta property="og:title" content="Apache的BeanUtils、Spring的BeanUtils、Mapstruct、BeanCopier对象拷贝">
<meta property="og:url" content="http://yoursite.com/2020/07/11/012/index.html">
<meta property="og:site_name" content="乐游さん 的博客~">
<meta property="og:description" content="在项目中，尤其是在服务层，经常要将服务中的Dto实体对象拷贝到Entity对象用于前端展示。反过来也是一样，需要将前端请求对象转换为服务端的数据对象。现在市面上有很多这样的工具包，比如spring框架中就自带了BeanUtils，使我们进行这样的数据操作十分简单快捷。但是一直以来却没有关注到对象属性的拷贝性能问题，最近在想：单个对象的拷贝是快速的，可以不在意太多性能问题，可是如果数量级变大了会怎样">
<meta property="article:published_time" content="2020-07-11T12:10:00.000Z">
<meta property="article:modified_time" content="2020-07-11T12:10:00.000Z">
<meta property="article:author" content="乐游">
<meta property="article:tag" content="JAVA bean spring 对象拷贝">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2020/07/11/012/"/>





  <title>Apache的BeanUtils、Spring的BeanUtils、Mapstruct、BeanCopier对象拷贝 | 乐游さん 的博客~</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?0492d48b6af5d10264fc93e94120c17c";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
     

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">乐游さん 的博客~</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">一直来自北方的程序猿 ~ </h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/07/11/012/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="乐游">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/WechatIMG22.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="乐游さん 的博客~">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">Apache的BeanUtils、Spring的BeanUtils、Mapstruct、BeanCopier对象拷贝</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-11T20:10:00+08:00">
                2020-07-11
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2020-07-11T20:10:00+08:00">
                2020-07-11
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JAVA/" itemprop="url" rel="index">
                    <span itemprop="name">JAVA</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/07/11/012/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2020/07/11/012/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 阅读次数
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p>在项目中，尤其是在服务层，经常要将服务中的Dto实体对象拷贝到Entity对象用于前端展示。反过来也是一样，需要将前端请求对象转换为服务端的数据对象。现在市面上有很多这样的工具包，比如spring框架中就自带了BeanUtils，使我们进行这样的数据操作十分简单快捷。但是一直以来却没有关注到对象属性的拷贝性能问题，最近在想：单个对象的拷贝是快速的，可以不在意太多性能问题，可是如果数量级变大了会怎样呢？如果数量级到达了百万级别，会出现什么样的情况呢？</p>
<a id="more"></a>

<p>带着心中的疑问，我首先梳理出来现在有哪些对象拷贝的方式：</p>
<ol>
<li>Apache的BeanUtils：BeanUtils是Apache commens组件里面的成员，由Apache提供的一套开源api，用于简化对javaBean的操作，能够对基本类型自动转换。</li>
<li>Spring的BeanUtils：BeanUtils是Spring框架提供的对Java反射和自省API的包装。其主要目的是利用反射机制对JavaBean的属性进行处理。</li>
<li>Mapstruct：<blockquote>
<p>MapStruct是一个Java 注释处理器，用于为Java Bean类生成类型安全和高性能的映射器。它使您不必手工编写映射代码，这是一个繁琐且容易出错的任务。该生成器具有合理的默认值和许多内置的类型转换，但是在配置或实现特殊行为时，它会自动退出。<br>与运行时工作的映射框架相比，MapStruct具有以下优点：</p>
<ul>
<li>通过使用普通方法调用而不是反射来快速执行</li>
<li>编译时类型安全。只能映射彼此映射的对象和属性，因此不会将订单实体意外映射到客户DTO等。</li>
<li>自包含代码 -没有运行时依赖项</li>
<li>如果发生以下情况，则在构建时清除错误报告：<ul>
<li>映射不完整（并非所有目标属性都被映射）</li>
<li>映射不正确（找不到正确的映射方法或类型转换）</li>
</ul>
</li>
<li>易于调试的映射代码（或手动编辑，例如在生成器中有错误的情况下）<br><a href="https://github.com/mapstruct/mapstruct" target="_blank" rel="noopener">github mapstruct/mapstruct</a></li>
</ul>
</blockquote>
</li>
</ol>
<ol start="4">
<li>BeanCopier：BeanCopier是Cglib包中的一个类，用于对象的复制。目标对象必须先实例化  而且对象必须要有setter方法。  </li>
</ol>
<hr>
<p>时间出真知，我使用的是相同的数据集，对每种方式都进行了测试。实体类如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">@Data</span><br><span class="line">public class UserVo &#123;</span><br><span class="line"></span><br><span class="line">    private String id;</span><br><span class="line"></span><br><span class="line">    private String name;</span><br><span class="line"></span><br><span class="line">    private Integer age;</span><br><span class="line"></span><br><span class="line">    private String city;</span><br><span class="line"></span><br><span class="line">    private String sex;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最终的测试结果如下：</p>
<table>
<thead>
<tr>
<th>数据量</th>
<th>Apache</th>
<th>Spring</th>
<th>MapStruct</th>
<th>BeanCopier</th>
</tr>
</thead>
<tbody><tr>
<td>100w</td>
<td>391ms</td>
<td>250ms</td>
<td>45ms</td>
<td>57ms</td>
</tr>
<tr>
<td>10w</td>
<td>82ms</td>
<td>34ms</td>
<td>8ms</td>
<td>10ms</td>
</tr>
<tr>
<td>1w</td>
<td>30ms</td>
<td>19ms</td>
<td>2ms</td>
<td>7ms</td>
</tr>
<tr>
<td>1k</td>
<td>15ms</td>
<td>6ms</td>
<td>1ms</td>
<td>5ms</td>
</tr>
<tr>
<td>100</td>
<td>5ms</td>
<td>3ms</td>
<td>1ms</td>
<td>4ms</td>
</tr>
<tr>
<td>10</td>
<td>2ms</td>
<td>1ms</td>
<td>1ms</td>
<td>4ms</td>
</tr>
</tbody></table>
<p>根据测试结果，我们可以得出在速度方面，MapStruct是最好的，执行速度是 Apache BeanUtils 的10倍、Spring BeanUtils 的 4-5倍、和 BeanCopier 的速度差不多。<br>由此可以看出，在大数据量级的情况下，MapStruct 和 BeanCopier 都有着较高的性能优势，其中 MapStruct 尤为优秀。如果你仅是在日常处理少量的对象时，选取哪个其实变得并不重要，但数据量大时建议还是使用MapStruct 或 BeanCopier 的方式，提高接口性能。  </p>
<p>当然，这个数据并没有考虑占用的内存和CPU的资源问题，仅仅是测试了在相同环境下的执行速度。  </p>
<p>最后，如果你问我在日常选取哪种方式？我当然是选择使用 Spring 的 BeanUtils 了。虽然它的性能不是最优的，但是我日常也不会出现数十万级数据量的情况，Spring BeanUtils 对我来说完全够用了，同时在使用spring时不必再引入新的依赖包，何乐而不为不呢。所以来说，适用于自身场景的才是最好的，不必要过分追求性能。<br>但当有一天你遇到需要处理较大数据量级的对象时，请记得还有性能更加优秀的MapStruct 和 BeanCopier 供你选择。  </p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JAVA-bean-spring-%E5%AF%B9%E8%B1%A1%E6%8B%B7%E8%B4%9D/" rel="tag"># JAVA bean spring 对象拷贝</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/07/09/011/" rel="next" title="git commit 使用及规范">
                <i class="fa fa-chevron-left"></i> git commit 使用及规范
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/12/07/013/" rel="prev" title="docker、containerd的关系">
                docker、containerd的关系 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  <div>
    
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------ 本文结束------</div>
    
</div>
    
  </div>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/WechatIMG22.jpeg"
                alt="乐游" />
            
              <p class="site-author-name" itemprop="name">乐游</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2020 &mdash; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">乐游</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  <script src="//cdn.jsdelivr.net/npm/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'ry4r48Li8ylactoROUmqjh7M-gzGzoHsz',
        appKey: 'vBcOR0V5lfk22hVzx04wUI57',
        placeholder: 'ヾﾉ≧∀≦)o 来呀！吐槽一番吧！',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
